package com.gitee.candy.string;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UrlUtil {

    /**
     * 获取客户端ip
     *
     * @param request
     * @return
     */
    public static String getCustomerIP(HttpServletRequest request) {

        String userip = request.getHeader("forwarded"); //格式 Forwarded: for=192.0.2.43,for=[2001:db8:cafe::17],for=unknown
        if (userip != null && userip.length() != 0 && !"unknown".equalsIgnoreCase(userip)) {
            if (userip.indexOf(",") > 0) {//如果有多个ip，则取第一个ip
                String userips[] = userip.split(",");
                for (int i = 0; i < userips.length; i++) {
                    if (userips[i].split("=")[0].equals("for") && userips[i].split("=")[1].indexOf(".") > 0) {//判断ip格式
                        userip = userips[i].split("=")[1];
                        break;
                    }
                }
            } else {
                if (userip.split("=")[0].equals("for") && userip.split("=")[1].indexOf(".") > 0) {//判断ip格式
                    userip = userip.split("=")[1];
                } else {
                    userip = null;
                }
            }
        }
        //查询代理
        if (userip == null || userip.length() == 0 || "unknown".equalsIgnoreCase(userip)) {
            String userip_x = request.getHeader("x-forwarded-for");   //格式X-Forwarded-For: client1, proxy1, proxy2
            if (userip_x != null && userip_x.length() != 0 && !"unknown".equalsIgnoreCase(userip_x)) {
                if (userip_x.indexOf(",") > 0 || userip_x.indexOf(";") > 0) {
                    //暂时去掉下面的方式
                    //userip = request.getHeader("Client-IP");
                    String userips[] = null;
                    if (userip_x.indexOf(",") > 0) {//如果有多个
                        userips = userip_x.split(",");
                    } else if (userip_x.indexOf(";") > 0) {
                        userips = userip_x.split(";");
                    }
                    for (int i = 0; i < userips.length; i++) {
                        if ((userip == null || userip.length() == 0 || "unknown".equalsIgnoreCase(userip)) && userips[i].indexOf(".") > 0) {//判断ip格式
                            userip = userips[i];
                            break;
                        }
                    }
                } else {
                    userip = userip_x;
                }
            }
        }
        if (userip == null || userip.length() == 0 || "unknown".equalsIgnoreCase(userip)) {
            userip = request.getHeader("Client-IP");
        }
        if (userip == null || userip.length() == 0 || "unknown".equalsIgnoreCase(userip)) {
            userip = request.getHeader("Proxy-Client-IP");
        }
        if (userip == null || userip.length() == 0 || "unknown".equalsIgnoreCase(userip)) {
            userip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (userip == null || userip.length() == 0 || "unknown".equalsIgnoreCase(userip)) {
            userip = request.getRemoteAddr();
        }
        //如果代理IP是局域网IP
        if ((userip.substring(0, 2).equals("0.")) || (userip.substring(0, 3).equals("10.")) || (userip.substring(0, 4).equals("127.")) || (userip.substring(0, 4).equals("192.")) || (userip.substring(0, 4).equals("172."))) {
            userip = request.getRemoteAddr();
        }
//        //如果代理IP是局域网IP
//        if ((userip.substring(0, 2).equals("0.")) || (userip.substring(0, 3).equals("10.")) || (userip.substring(0, 4).equals("127.")) || (userip.substring(0, 4).equals("192.")) || (userip.substring(0, 4).equals("172.")))
//        {
//            //如果从代理中没有找到有效的ip，最后查request.getRemoteAddr()，有可能还是局域网ip，因为有可能客户端使用了Apache,Squid等反向代理软件
//            userip = "114.114.114.114";
//        }

        return userip;
    }

    /**
     * 获取url的完整域名
     *
     * @param url
     * @return domain
     */
    public static String getFullDomain(String url) {
        Pattern p = Pattern.compile("[^//]*?\\.(com|cn|net|org|biz|info|cc|tv|la|me|tel|mobi|asia|name|hk|so|gd|top)", Pattern.CASE_INSENSITIVE);
        Matcher matcher = p.matcher(url);
        matcher.find();
        return matcher.group();
    }

    public static String getDomain(String url) {
        Pattern p = Pattern.compile("(\\w*\\.?){1}\\.(com.cn|net.cn|gov.cn|org\\.nz|org.cn|com|net|org|gov|cc|biz|info|cn|co)", Pattern.CASE_INSENSITIVE);
        Matcher matcher = p.matcher(url);
        matcher.find();
        String firstDomain = matcher.group();
        return firstDomain;
    }

    public static Boolean dealRefer(String refer) {
        Boolean flag = false;
        String regx = "[1-9]+,[1-9]+";
        if (!"".equals((refer == null || "null".equals(refer)) ? "" : refer) && refer.indexOf("?") != -1) {
            String regVal = refer.substring(refer.indexOf("?") + 1);
            Pattern p = Pattern.compile(regx);
            Matcher m = p.matcher(regVal);
            flag = m.find();
        }

        return flag;
    }

    /**
     * 获取是移动还是pc
     *
     * @param request
     * @return int 1:移动端 0：pc端
     */
    public static int isPcOrMobile(HttpServletRequest request) {
        String userAgent = request.getHeader("USER-AGENT").toLowerCase();
        int mobileType = 0;
        // \b 是单词边界(连着的两个(字母字符 与 非字母字符) 之间的逻辑上的间隔),
        // 字符串在编译时会被转码一次,所以是 "\\b"
        // \B 是单词内部逻辑间隔(连着的两个字母字符之间的逻辑上的间隔)
        String phoneReg = "\\b(ip(hone|od)|android|opera m(ob|in)i" + "|windows (phone|ce)|blackberry"
                + "|s(ymbian|eries60|amsung)|p(laybook|alm|rofile/midp"
                + "|laystation portable)|nokia|fennec|htc[-_]"
                + "|mobile|up.browser|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";
        String tableReg = "\\b(ipad|tablet|(Nexus 7)|up.browser" + "|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";

        //移动设备正则匹配：手机端、平板
        Pattern phonePat = Pattern.compile(phoneReg, Pattern.CASE_INSENSITIVE);
        Pattern tablePat = Pattern.compile(tableReg, Pattern.CASE_INSENSITIVE);
        if (null == userAgent) {
            userAgent = "";
        }
        // 匹配
        Matcher matcherPhone = phonePat.matcher(userAgent);
        Matcher matcherTable = tablePat.matcher(userAgent);
        if (matcherPhone.find() || matcherTable.find()) {
            mobileType = 1;//说明是移动设备 二维码
        } else {
            mobileType = 0;
        }
        return mobileType;
    }
}
